<script setup lang="ts">
import { ref } from 'vue'
import { useArticleStore } from '../../store/articel'
import useArticle from '../../composition/useArticel'
import useUpload from '../../composition/useUpload'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/userStore'

const userStore = useUserStore()
const userInfo = userStore.userInfo

const router = useRouter()
const articleStore = useArticleStore()
const articel = ref(articleStore.articel)

const onClickLeft = () => history.back()

const show = ref(false)
const fileList = ref([{ url: articel.value.previewImg, isImage: true }])

const { addArticle } = useArticle()
const { uploadFile } = useUpload()
const afterRead = async (file: any) => {
   let params = new FormData()
   params.append('file', file.file)
   const res = await uploadFile(params)
   articel.value.previewImg = res.data.url
}

const add = async () => {
   if (!articel.value.previewImg) return showToast('请上传封面')
   await addArticle(articel.value)
   articleStore.articel = {
      title: '',
      content: '',
      previewImg: '',
      categoryId: 0
   }
   router.push({ name: 'me.article', params: { userId: userInfo?.id } })
}
</script>

<template>
   <div class="p-3">
      <van-nav-bar
         title="文章详情"
         right-text="发表"
         left-text="编辑"
         left-arrow
         @click-left="onClickLeft"
         @click-right="show = true" />
      <h1 class="text-2xl font-bold pt-4">{{ articel.title }}</h1>
      <v-md-preview :text="articel.content"></v-md-preview>
   </div>

   <van-action-sheet v-model:show="show" title="标题">
      <div class="content">
         <van-uploader class="mb-6" v-model="fileList" :after-read="afterRead" :max-count="1" />
         <van-button class="w-[100px] h-[100px]" type="primary" @click="add" block>确定发表</van-button>
      </div>
   </van-action-sheet>
</template>

<style scoped lang="scss">
.content {
   padding: 16px 16px;
   display: flex;
   align-items: center;
   flex-direction: column;

   ::v-deep .van-uploader__preview-image {
      width: 150px;
      height: 150px;
   }
}
</style>
